package cn.zhenglili.uflodemo.provider.assignee;

import cn.zhenglili.uflodemo.entity.SysRole;
import cn.zhenglili.uflodemo.service.feign.UserService;
import cn.zhenglili.uflodemo.utils.SpringContextUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.assign.AssigneeProvider;
import com.bstek.uflo.process.assign.Entity;
import com.bstek.uflo.process.assign.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wanheng
 * @since 2020/10/4
 */
@Component
@Slf4j
public class RoleAssigneeProviderImpl implements AssigneeProvider {

    @Resource
    private UserService userService;

    @Override
    public boolean isTree() {
        return false;
    }

    @Override
    public String getName() {
        return "指定角色";
    }

    @Override
    public void queryEntities(PageQuery<Entity> pageQuery, String s) {
        log.info("getRoles");
        // 查询所有角色
        List<SysRole> sysRoleList = userService.queryall().getResult();
        int index = pageQuery.getPageIndex();
        int size = pageQuery.getPageSize();
        // 返回的角色实体列表
        List<Entity> entitys = new ArrayList();
        Entity parameter = pageQuery.getQueryParameter();
        String id = null;
        if (parameter != null) {
            id = parameter.getId();
        }
        // 分页 index为第i页
        int max = 0;
        if (sysRoleList.size() > index * size) {
            max = index * size;
        } else {
            max = sysRoleList.size();
        }
        for (int i = (index - 1) * size; i < max; ++i) {
            SysRole sysRole = sysRoleList.get(i);
            if (id == null || String.valueOf(i).equals(id)) {
                Entity entity = new Entity(sysRole.getId(), sysRole.getRoleName());
                entitys.add(entity);
            }
        }
        pageQuery.setResult(entitys);
        pageQuery.setRecordCount(sysRoleList.size());
    }

    /**
     * 根据角色id获取用户
     * @param roleId
     * @param context
     * @param processInstance
     * @return
     */
    @Override
    public Collection<String> getUsers(String roleId, Context context, ProcessInstance processInstance) {
        log.info("getUsers");
        log.info(roleId);
        List<String> users = userService.queryUserByRoleId(roleId).getResult();
        for (String user : users) {
            log.info("user-->" + user);
        }
        return users;
    }

    @Override
    public boolean disable() {
        return false;
    }
}
